<template>
  <van-popup
    v-model:show="popupShow"
    round
    position="bottom"
    safe-area-inset-bottom
    @close="onPopupClose()"
    @opened="onPopupOpened()"
  >
    <van-cell-group inset>
      <van-field
        ref="RefField"
        v-model="username"
        center
        clearable
        maxlength="10"
        label="个性昵称"
        placeholder="请输入你的个性昵称"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            :loading="chatStore.connecting"
            @click="handleGo()"
          >
            Go!
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
  </van-popup>
</template>

<script setup>
  import { useChatStore } from '@/store/chat'

  const props = defineProps({ show: Boolean })
  const emits = defineEmits(['update:show', 'login'])

  const chatStore = useChatStore()

  const popupShow = computed({
    get: () => props.show,
    set: val => emits('update:show', val),
  })

  const username = ref('')

  const RefField = ref()
  const onPopupClose = () => {
    username.value = ''
  }
  const onPopupOpened = async () => {
    await nextTick()

    RefField.value?.focus()
  }

  const handleGo = () => {
    if (chatStore.connecting) return
    chatStore.openConnect(username.value)
    popupShow.value = false
  }

  // emits('login', username)
</script>

<style lang="less" scoped></style>
